package tsing.javase.stream;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

class ElementDemo {
    private int id;
    private String name;

    public ElementDemo(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }


    public static void main(String[] args) {
        List<ElementDemo> elements = Arrays.asList(new ElementDemo(1, "A"), new ElementDemo(2, "B"), new ElementDemo(3, "C"),
                                               new ElementDemo(1, "A"), new ElementDemo(4, "D"), new ElementDemo(2, "B"));

        Map<String, Long> elementCounts = elements.stream()
                                                 .collect(Collectors.groupingBy(element -> element.getId() + "#" + element.getName(),
                                                                               Collectors.counting()));

        List<ElementDemo> duplicates = elementCounts.entrySet().stream()
                                             .filter(entry -> entry.getValue() > 1)
                                             .map(Map.Entry::getKey)
                                             .map(idNamePair -> elements.stream()
                                                                       .filter(element -> idNamePair.equals(element.getId() + "#" + element.getName()))
                                                                       .findFirst()
                                                                       .orElse(null))
                                             .collect(Collectors.toList());

        duplicates.forEach(System.out::println);



    }
}
